/**
 * jims.
 */
package com.jims.master.modules.sys.service;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import com.jims.master.common.config.Global;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.common.utils.SynchroDataUtils;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.entity.Company;
import com.jims.master.modules.sys.entity.SysService;
import com.jims.master.modules.sys.utils.DictUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
@Transactional(readOnly = false)
public class CompanyService extends CrudService<CompanyDao, Company> {

    @Autowired
    private CompanyDao companyDao;

    @Autowired
    private OrgDeptService orgDeptService;

	public List<Company> findList(){
		return super.findList(new Company());
	}

	@Transactional(readOnly = false)
	public int save(Company company) {
		return super.save(company);
	}

	@Transactional(readOnly = false)
	public int delete(Company company) {
        return super.delete(company);
 	}

    /**
     *
     * @param company
     * @return
     */
    public List<SysService> findServiceByOrg(Company company) {
         return this.companyDao.findServiceByOrg(company);
    }
    @Transactional(readOnly = false)
    public int saveCompanyVsService(Company c) {
        return this.companyDao.saveCompanyVsService(c);
    }
    @Transactional(readOnly = false)
    public int deleteFromCompanyVsService(Company company) {
        return this.companyDao.deleteFromCompanyVsService(company);
    }

    @Transactional(readOnly = false)
    public int middleSaveService(String[] serviceIds,Company company) {
        int newNum=0;
        for (int i = 0; i < serviceIds.length; i++) {
            Company c=new Company();
            c.setCompanyId(company.getId());
            c.setServiceId(serviceIds[i]);
            c.preInsert();
            newNum += saveCompanyVsService(c);
        }
        return newNum;
    }

    /**
     * 同步人力资源处组织机构（webService接口和AMQ通用的方法）
     * * @param type 类型   add 新增    update 修改   delete 删除
     *
     * @return
     * @author yangruidong
     */
    @Transactional(readOnly = false)
    public String synchroOrg(String type, String inputLine) {
        List<Map<String, Object>> result;
        //判断是AMQ新增还是webService接口同步数据
        if (StringUtils.isBlank(inputLine)) {
            String dict = DictUtils.getDictValue("同步机构", "org_data", "");
            //访问人力资源同步数据的路径
            String url = Global.getConfig("hrm_ip") + dict;
            result = convertList(SynchroDataUtils.getJsonByUrl(url));
        } else {
            result = convertList(inputLine);
        }
        if (result != null) {
            List<Company> companys = findList(new Company());
            Map<String, Company> deptMap = Maps.uniqueIndex(companys, new Function<Company, String>() {
                @Override
                public String apply(Company company) {
                    return company.getId();
                }
            });
            for (int i = 0; i < result.size(); i++) {
                Map<String, Object> map = result.get(i);
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    Company company = (Company) entry.getValue();
                    //使用webService同步数据以及修改数据
                    if (deptMap.get(company.getId()) == null) {
                        company.setDelFlag("0");
                        dao.insert(company);
                        if(StringUtils.equalsIgnoreCase("add", type)) {
                            orgDeptService.synchroDept(type,company.getId(),"");
                        }
                    } else {
                        Company updateCompany = deptMap.get(company.getId());
                        company.setParentId(updateCompany.getParentId());
                        company.setDelFlag("0");
                        save(company);
                    }
                }
            }
            return "success";
        }
        return null;
    }


    /**
     * 转换，将人力资源传递的数据转成list集合
     *
     * @param json 人力资源地址,或者是AMQ传递的json数据
     * @return
     * @author yangruidong
     */
    public List<Map<String, Object>> convertList(String json) {
        Map<String, String[]> replaceMap = new HashMap<>();
        String namespace = Company.class.getName();
        replaceMap.put("id", new String[]{namespace, "id"});
        replaceMap.put("name", new String[]{namespace, "orgName"});
        replaceMap.put("parentId", new String[]{namespace, "parentId"});
        replaceMap.put("sort", new String[]{namespace, "sort"});
        replaceMap.put("delFlag", new String[]{namespace, "delFlag"});
        replaceMap.put("createBy", new String[]{namespace, "createBy.id"});
        replaceMap.put("createDate", new String[]{namespace, "createDate"});
        replaceMap.put("updateBy", new String[]{namespace, "updateBy.id"});
        replaceMap.put("updateDate", new String[]{namespace, "updateDate"});
        return SynchroDataUtils.getDataByJson(json, replaceMap);
    }
}
